<?php
require 'login-libs.php';

//check that the email address is provided and valid
if (!isset($_REQUEST['email']) || $_REQUEST['email'] == '' || !filter_var($_REQUEST['email'], FILTER_VALIDATE_EMAIL)) {
	login_redirect($url, 'noemail');
}

//check that password is provided
if (!isset($_REQUEST['password']) || $_REQUEST['password'] == '') {
	login_redirect($url, 'nopassword');
}

//check that the email/password combination matches a row in the table
$password = md5($_REQUEST['password']);
$r = $database->dbRow('SELECT email, password FROM user_accounts
			WHERE email = "' . addslashes($_REQUEST['email']) . '"
			AND password = "' . $password . '"
			AND active'
);
if ($r == false) {
	login_redirect($url, 'loginfailed');
}

//***** succes!
//update last logged in time in db
$q = "UPDATE user_accounts
		SET last_login = NOW()
		WHERE email = '" . addslashes($_REQUEST['email']) . "' ";
$database->dbQuery($q);

//set userdata in session
$user = $database->dbRow('SELECT * FROM user_accounts
			WHERE email = "' . addslashes($_REQUEST['email']) . '"
			AND active'
);
$_SESSION['userdata'] = $user;

//set permissions in session
$administrator = Administrator::getInstance();
$permissions = $administrator->userAssignedPermissions($user['id']);
$plugin = '';
foreach($permissions as $p){
	if($p['plugin'] != $plugin)	$_SESSION['userdata']['permissions'][$p['plugin']] = array();
	$_SESSION['userdata']['permissions'][$p['plugin']][$p['name']] = true;
	$plugin = $p['plugin'];
}

login_redirect($url, 'succes');